<?php

namespace App\Http\Controllers\ChinaBank;

use App\Models\ChinaBank\CardTypeModel;
use App\Models\ChinaBank\TokenModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\ChinaBank\CardModel;


class BankApiController extends Controller
{
    private static $account;
    private static $password;
    private static $secret;
    private static $encAccount;

    public function __construct()
    {
        $chinabankConfig = config("chinabank");
        self::$account = $chinabankConfig['account'];
        self::$password = $chinabankConfig['password'];
        self::$secret = $chinabankConfig['secret'];
    }


    public static function timestamp($time=0){
        if($time == 0)
        {
            $time = time();
        }

        return date('YmdHis',$time);
    }

    public static function res($code,$msg,array $data = []){

        $base = ["reason"=>$msg,"result"=>$code];
        if(count($data) > 0){
            $data = array_merge($base,$data);
        }else{
            $data = $base;
        }

        self::log($data);

        $data = self::encrypt(\GuzzleHttp\json_encode($data));
        return $data;
    }

    public static function digest($timestamp)
    {
        $str = self::$account . "$" . self::$password . "$" . $timestamp;
        return base64_encode(sha1($str));
    }


    public static function encrypt($data){
        return self::passwordres($data,'encrypt');
    }

    public static function decrypt($str){
        $data =  self::passwordres($str,'decrypt');
        if($data != false){
            self::log($data);
        }
        return $data;
    }

    public static function passwordres($str,$type)
    {
        $file = public_path('temp/'.time().rand(1000,9999).".txt");
        $app = "App";
        $appPath = dirname(public_path("")).DIRECTORY_SEPARATOR."java".DIRECTORY_SEPARATOR."chinabank";
        $str = base64_encode($str);
        $cmd = "cd $appPath && /usr/java/jdk1.8.0_131/bin/java $app $type $file ".$str;
        self::log($cmd);
        exec($cmd);
        if(!file_exists($file)){
            return false;
        }
        return   file_get_contents($file);
    }
    public static function log($data,$url=''){

        if(is_array($data))
        {
            $data = \GuzzleHttp\json_encode($data,JSON_UNESCAPED_UNICODE);
        }

        $str  = "";
        if($url){
            $str = $url."\n";
        }
        $data = $str.self::timestamp()."\n".$data."\n\n";
        file_put_contents("log.txt",$data,FILE_APPEND);
    }

    public static function createToken()
    {
        $time   = time();
        $token  = md5("tongzhu".$time);
        $time   = $time + 2 * 60 * 60;
        TokenModel::where('token_id',1)->update(["token"=>$token,"valid_time"=>$time]);
        $time   = self::timestamp($time);
        return ["token"=>$token,"time"=>$time];
    }

    public static function checkToken($token){

    }
    /**
     * 授权操作
     * @param $request Request
     * @return mixed
     * */
    public function createAuth(Request $request){
        self::log($request->all(),$request->url());
        $appId  = $request->input('appId');
        $secret = $request->input('secret');
        //检查用户信息
        $secret = self::decrypt($secret);
        if($secret == false){
            return self::res("01","无法解密数据");
        }
        $secret = \GuzzleHttp\json_decode($secret);

        $mydigest = self::digest($secret->timeStamp);
        if($mydigest != $secret->digest)
        {
            return self::res("04","摘要验证失败");
        }

        $timestamp = self::timestamp();
        $token  = self::createToken();
        $tokenInfo  = [
            "tokenId"   => $token['token'],
            "digest"    => self::digest($timestamp),
            "expireTime" => $token['time'] //token有效期，两个小时
        ];
        return self::res("00","OK",["tokenInfo"=>$tokenInfo]);
    }


    /**
     * 获取电子券
     * */
    public function useElecCard(Request $request){
        self::log($request->all(),$request->url());
        $token  = $request->input('tokenId');
        $secret = trim($request->input('secret'));
        $secret = self::decrypt($secret);
        if($secret == false){
            return self::res("01","无法解码数据");
        }
        $secret = \GuzzleHttp\json_decode($secret);

        $customerOrderNum   = $secret->customerOrderNum;
        $cardNum            = (int) $secret->cardNum;
        //检查改订单号是否已经领取
        $cards = CardModel::where('bank_order_id',$customerOrderNum)->get();

        if(count($cards) == 0){
            //没有领取取出一张空的券
            $cards   = CardModel::whereNull('bank_order_id')
                ->where('type',$secret->elecTypeId)
                ->limit($cardNum)->get();

            if(count($cards) < $cardNum)
            {
                return self::res("08","卡券库存不足");
            }

            //修改卡券为已经领取
            foreach($cards as $card){
                $updateInfo = [
                    'bank_order_id' => $customerOrderNum,
                    'bank_user_id'  => $secret->idNo
                ];
               CardModel::where('card_id',$card->card_id)->update($updateInfo);
            }
        }

        //获取卡券类型

        $cardList = [];
        foreach($cards as $card){

            $type = CardTypeModel::find($card->type);
            $cardList[] = [
                "code"      => $card->account,
                "pwd"       => $card->password,
                "vaildDate" => $card->valid_date,
                "elecTypeId"=> (string)$card->type,
                "elecName"  => $type->name,
                "voucherType" => 0 //0:卡密类型
            ];
        }

        //分配卡券
        $useElecCardResult = [
            "customerOrderNum"  => $customerOrderNum,
            "orderNum"          => "",
            "listCard"          => $cardList
        ];

        return self::res("00","OK",['useElecCardResult'=>$useElecCardResult]);
    }

    /**
     * 查询电子券
     * */
    public function queryElecCard(Request $request){
        self::log($request->all(),$request->url());
        $token  = $request->input('tokenId');
        $secret = $request->input('secret');
        $secret = self::decrypt($secret);
        $secret = json_decode($secret);
        $customerOrderNum = $secret->customerOrderNum;

        $cards = CardModel::where('bank_order_id',$customerOrderNum)->get();
        $cardList = [];
        foreach($cards as $card){
            $type   = CardTypeModel::find($card->type);
            $cardList[] = [
                "code"          => $card->account,
                "pwd"           => $card->password,
                "vaildDate"     => $card->valid_date,
                "elecTypeId"    => (string)$card->type,
                "elecName"      => $type->name,
                "voucherType"   => 0,
                "customerOrderNum" => $card->bank_order_id,
                "orderNum"      => ''
            ];
        }

        $data = [
            "pageCount" => 1,
            "pageNum"   => 1,
            "pageSize"  => 1,
            "customerOrderNum" => $customerOrderNum,
            "totalCount" => count($cards),
            "listCard"  => $cardList
        ];

        return self::res("00","ok",$data);
    }

    /**
     * 批量核销电子券
     * */
    public function docheckTickets(Request $request){
        self::log($request->all(),$request->url());
        $token  = $request->input('tokenId');
        $secret = $request->input('secret');
        $secret = self::decrypt($secret);
        $secret = json_decode($secret);

        $cards  = $secret->listCard;

        foreach($cards as &$card){

            //检查卡券是否使用
            $myCard = CardModel::where('bank_order_id',$card->customerOrderNum)
                ->where('account',$card->code)
                ->first();

            $card->codeStatus = $myCard->order_id > 0 ? "1" : "0";
        }

        $data   = [
            "RowNum"    => count($cards),
            "listCard"  => $cards
        ];

        return self::res("00","OK",$data);
    }
}
